﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using SenseTimeTracker.Properties;
using StedySoft.SenseSDK;

namespace SenseTimeTracker.Main
{
	public class UpdateForm : ITranslucentForm
	{
		[DllImport("Coredll.dll", EntryPoint = "GetDC")]
		public static extern IntPtr GetDC(IntPtr hWnd);
		[DllImport("coredll")]
		internal static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
		[DllImport("coredll")]
		private static extern bool BitBlt(
			IntPtr hdcDest, // handle to destination DC
			int nXDest, // x-coord of destination upper-left corner
			int nYDest, // y-coord of destination upper-left corner
			int nWidth, // width of destination rectangle
			int nHeight, // height of destination rectangle
			IntPtr hdcSrc, // handle to source DC
			int nXSrc, // x-coordinate of source upper-left corner
			int nYSrc, // y-coordinate of source upper-left corner
			Int32 dwRop // raster operation code
			);

		private Bitmap bitmap = null;

		public delegate void UpdateFormDelegate();
		private UpdateFormDelegate updateForm;
		//private SenseLabelControl testLabel;
		private Label testLabel;

		private Bitmap logo;
		private string newVersionText;

		protected override void OnLoad(EventArgs e)
		{
			Assembly assembly = Assembly.GetExecutingAssembly();
			logo = new Bitmap(assembly.GetManifestResourceStream("SenseTimeTracker.Resources.Logo.bmp"));
			newVersionText = Resources.CheckingNewVersionPending;
			updateForm = new UpdateFormDelegate(Invalidate);

			Uri codeplexUri = new Uri("http://sensetimetracker.codeplex.com/releases");
			WebRequest request = HttpWebRequest.Create(codeplexUri);
			request.BeginGetResponse(ResponseCallback, request);
		}

		private void ResponseCallback(IAsyncResult asynchronousResult)
		{
			try
			{
				HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
				HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
				Stream responseStream = response.GetResponseStream();
				StreamReader streamReader = new StreamReader(responseStream);
				string answer = streamReader.ReadToEnd();
				answer = answer.Substring(answer.IndexOf("Recommended Download"));
				answer = answer.Substring(answer.IndexOf("<div"));
				answer = answer.Substring(answer.IndexOf("<a"));
				answer = answer.Substring(answer.IndexOf(">") + 1);
				answer = answer.Substring(0, answer.IndexOf("</a>"));
				answer = answer.Substring(answer.IndexOf("V") + 1);
				answer = answer.Substring(0, answer.IndexOf(" ")).Trim();
				string[] version = answer.Split('.');
				int majorVersion = int.Parse(version[0]);
				int minorVersion = int.Parse(version[1]);
				Version currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
				if (currentVersion.Major < majorVersion || currentVersion.Major == majorVersion && currentVersion.Minor < minorVersion)
				{
					newVersionText = string.Format("{0}\r{1}: {2}", Resources.CheckingNewVersionAvailable, Resources.AssemblyVersion, answer);
				}
				else
				{
					newVersionText = Resources.CheckingNewVersionUpToDate;
				}
				responseStream.Close();
				response.Close();
			}
			catch
			{
				newVersionText = Resources.CheckingNewVersionError;
			}

			if (InvokeRequired)
			{
				Invoke(updateForm);
			}
			else
			{
				Invalidate();
			}
		}

		bool firstdraw = true;
		protected override void OnPaintBackground(PaintEventArgs e)
		{
			if (firstdraw)
			{
				base.OnPaintBackground(e);
				firstdraw = false;
			}
		}

		protected override void OnClick(EventArgs e)
		{
			Close();
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			ImageAttributes immageAttr = new ImageAttributes();
			immageAttr.SetColorKey(Color.Magenta, Color.Magenta);
			Rectangle logoRect = new Rectangle((Width - logo.Width) / 2, 200, logo.Width, logo.Height);
			e.Graphics.DrawImage(logo, logoRect, 0, 0, logo.Width, logo.Height, GraphicsUnit.Pixel, immageAttr);

			using (Brush brush = new SolidBrush(Color.White))
			using (Font font = new Font("HelveticaNeue LT 35 Thin", 7f, FontStyle.Regular))
			using (Font versionFont = new Font("HelveticaNeue LT 35 Thin", 6f, FontStyle.Regular))
			{
				string version = string.Format("{0}: {1}", Resources.AssemblyVersion, Assembly.GetExecutingAssembly().GetName().Version);
				SizeF versionSize = e.Graphics.MeasureString(version, versionFont);
				e.Graphics.DrawString(version, versionFont, brush, logoRect.Right - versionSize.Width, logoRect.Bottom + 2);

				SizeF newVersionTextSize = e.Graphics.MeasureString(newVersionText, font);
				if (bitmap == null)
				{
					// Get the handle of the form's device context and create compatible
					// graphics and bitmap objects
					IntPtr desktopDC = GetDC(Handle);
					bitmap = new Bitmap(Width, 30);
					Graphics graphics = Graphics.FromImage(bitmap);

					// Get the handle to the graphics object's device context.
					IntPtr bitmapDC = graphics.GetHdc();

					// Copy the form to the bitmap
					BitBlt(bitmapDC, 0, 0, bitmap.Width, bitmap.Height, desktopDC, 0, logoRect.Bottom + (int)versionSize.Height + 20, 0x00CC0020 /*SRCCOPY*/);
					
					// Release native resources
					ReleaseDC(IntPtr.Zero, desktopDC);
					graphics.ReleaseHdc(bitmapDC);
					graphics.Dispose();

				}
				else
				{
					e.Graphics.DrawImage(bitmap, 0, logoRect.Bottom + (int)versionSize.Height + 20);
				}

				e.Graphics.DrawString(newVersionText, font, brush, (Width - newVersionTextSize.Width) / 2, logoRect.Bottom + versionSize.Height + 20);
			}
		}
	}
}

